﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Free2AskModel;
using LinqToExcel;
using System.IO;
using LinqToExcel.Domain;
using Free2AskWeb.Exceptions;

namespace Free2AskWeb.Controllers
{
    //class Member
    //{
    //    public string CardNo { get; set; }
    //    public string RealName { get; set; }
    //    public string Gender { get; set; }
    //}
    [HandleError]
    [Authorize(Roles="admin")]
    public class ACLController : Controller
    {
        private Free2AskDBEntities db = new Free2AskDBEntities();

        public ActionResult DeleteACLMember(int aclGroupID, string cardNo)
        {
            db.ACLMembers.Where(m => m.ACLGroupID == aclGroupID && m.CardNo == cardNo.Trim()).ToList().ForEach(m => db.DeleteObject(m));
            db.SaveChanges();
            return RedirectToAction("Details", new { id = aclGroupID });
        }

        public ActionResult ClearGroupMemebers(int aclGroupID)
        {
            db.ACLMembers.Where(m => m.ACLGroupID == aclGroupID).ToList().ForEach(m => db.DeleteObject(m));
            db.SaveChanges();
            return RedirectToAction("Details", new { id = aclGroupID });
        }

        [HttpPost]
        //[HandleError(View = "Error", ExceptionType = typeof(ACLMemeberAlreadyExistsException))]
        public ActionResult AddSingleACLMember(string realName, string cardNo, string gender, int aclGroupID)
        {
            var found = from m in db.ACLMembers
                        where m.ACLGroupID == aclGroupID && m.CardNo == cardNo
                        select m;
            if (found.Count() > 0)
            {
                throw new ACLMemeberAlreadyExistsException("Error: ACLMemeber already exists!");
                //return View();
            }
            else
            {
                ACLMember member = new ACLMember { RealName = realName, CardNo = cardNo, Gender = gender, ACLGroupID = aclGroupID };
                db.ACLMembers.AddObject(member);
                db.SaveChanges();

                return RedirectToAction("Details", new { id = aclGroupID });
            }
        }


        [HttpPost]
        public ActionResult AddACLMembers(HttpPostedFileBase file, int aclGroupID)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(path);


                var excel = new ExcelQueryFactory(path);
                //excel.FileName = ;
                excel.DatabaseEngine = DatabaseEngine.Ace;
                excel.AddMapping<ACLMember>(m => m.CardNo, "学号");
                excel.AddMapping<ACLMember>(m => m.RealName, "姓名");
                excel.AddMapping<ACLMember>(m => m.Gender, "性别");
                var members =from m in excel.Worksheet<ACLMember>()
                              select m;
                
                foreach (var x in members)
                {
                    x.ACLGroupID = aclGroupID;//arbitary
                    //System.Diagnostics.Debug.WriteLine(x.CardNo+","+x.RealName+","+x.Gender);
                    db.ACLMembers.AddObject(x);
                }
                db.SaveChanges();
            }

            // redirect back to the index action to show the form once again
            return RedirectToAction("Details", new { id = aclGroupID });   
        }
        //
        // GET: /ACL/

        public ViewResult Index()
        {
            return View(db.ACLGroups.ToList());
        }

        //
        // GET: /ACL/Details/5

        public ViewResult Details(int id)
        {
            ACLGroup aclgroup = db.ACLGroups.Single(a => a.ID == id);
            return View(aclgroup);
        }

        //
        // GET: /ACL/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /ACL/Create

        [HttpPost]
        public ActionResult Create(ACLGroup aclgroup)
        {
            if (ModelState.IsValid)
            {
                db.ACLGroups.AddObject(aclgroup);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(aclgroup);
        }
        
        //
        // GET: /ACL/Edit/5
 
        public ActionResult Edit(int id)
        {
            ACLGroup aclgroup = db.ACLGroups.Single(a => a.ID == id);
            return View(aclgroup);
        }

        //
        // POST: /ACL/Edit/5

        [HttpPost]
        public ActionResult Edit(ACLGroup aclgroup)
        {
            if (ModelState.IsValid)
            {
                db.ACLGroups.Attach(aclgroup);
                db.ObjectStateManager.ChangeObjectState(aclgroup, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(aclgroup);
        }

        //
        // GET: /ACL/Delete/5
 
        public ActionResult Delete(int id)
        {
            ACLGroup aclgroup = db.ACLGroups.Single(a => a.ID == id);
            return View(aclgroup);
        }

        //
        // POST: /ACL/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            ACLGroup aclgroup = db.ACLGroups.Single(a => a.ID == id);
            aclgroup.ACLMembers.ToList().ForEach(m => db.DeleteObject(m));
            db.ACLGroups.DeleteObject(aclgroup);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

    }
}